<?php

class AuthController extends Zend_Controller_Action
{
 
    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // action body
        $form = new Application_Form_Login();
        $request = $this->getRequest();
        
        $this->view->notifica = "";
        if ($request->isPost()) {
            if ($form->isValid($request->getPost())) {
                // do something here to log in
                if ($this->_process($form->getValues())) {
                    // We're authenticated! Redirect to the home page
                    $urlOptions = array('controller'=>'index', 'action'=>'index');
                      
                    /*
                    echo "<pre>";
                    print_r($form->getValues());
                    echo "</pre>";       
                    */
                    $this->_helper->redirector->gotoRoute($urlOptions,'admin');
                }else{
                    $this->view->notifica = '<p style="padding:2px;">Autenticazione fallita: username o password non corretti.</p>';
                }
            }
        }
        $this->view->form = $form;  
        
    }
    
    

protected function _process($values)
    {
        // Get our authentication adapter and check credentials

        $adapter = $this->_getAuthAdapter();

        $adapter->setIdentity($values['username']);
        $adapter->setCredential($values['password']);

        //$adapter->setCredentialTreatment('SHA1(CONCAT(?,salt))');

        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($adapter);

        if ($result->isValid()) {
            $user = $adapter->getResultRowObject();
            $auth->getStorage()->write($user);
            return true;
        }
        return false;
    }

    protected function _getAuthAdapter()
    {
        $administrator = new Application_Model_DbTable_Administrator();
        //$dbAdapter = Zend_Db_Table::getDefaultAdapter();
        $authAdapter = new Zend_Auth_Adapter_DbTable($administrator->getAdapter(),'administrator');
        
        $authAdapter->setTableName('utente')
            ->setIdentityColumn('login')
            ->setCredentialColumn('password');
            //->setCredentialTreatment('SHA1(CONCAT(?,salt))');
       return $authAdapter;
    }

    
    public function logoutAction()
    {
        // action body
        Zend_Session::namespaceUnset('id_persona');
        Zend_Auth::getInstance()->clearIdentity();
        $this->_helper->redirector('index'); // back to login page
    
    }    


}

